﻿<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>table 组件综合演示 - Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//unpkg.com/layui@2.11.0/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 自定义分页栏样式 */
        .layui-laypage {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
        }

        .navbar {
            display: none;
        }

        .layui-laypage a,
        .layui-laypage span {
            margin: 0 5px;
            padding: 0 10px;
            height: 30px;
            line-height: 30px;
            border: 1px solid #e2e2e2;
            border-radius: 3px;
            cursor: pointer;
        }

            .layui-laypage a:hover {
                color: #009688;
            }

        .layui-laypage .layui-laypage-curr {
            background-color: #009688;
            color: #fff;
        }

    </style>
</head>

<body>

    <!--查询-->
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" placeholder="请输入角色名称" name="Title" class="layui-input">
            </div>
            <button class="layui-btn layui-bg-blue" lay-submit lay-filter="search"> 查询</button>
            <button type="button" class="layui-btn layui-btn-normal" id="addRole">新增</button>

        </div>
    </form>

    <div style="padding: 16px;">
        <table class="layui-hide" id="test" lay-filter="test"></table>
    </div>


    <script type="text/html" id="toolDemo">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    </script>


    <!-- 新增/编辑对话框 -->
    <div id="addDialog" style="display: none; padding: 15px; width: 100%;overflow: auto;">
        <form class="layui-form" id="addForm" lay-filter="addForm">
            <table style="width:800px">
                <tr>
                    <td width="300px">
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width:100px">角色名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="roleName" lay-verify="required" placeholder="请输入内容" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width:100px">角色描述</label>
                            <div class="layui-input-block">
                                <input type="text" name="roleDesc" lay-verify="required" placeholder="请输入内容" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width:100px">是否启用</label>
                            <div class="layui-input-block">
                                <input type="checkbox" id="IsUsed" checked name="IsUsed" lay-skin="switch" lay-filter="switchTest"
                                       title="开关">
                            </div>
                        </div>
                    </td>
                </tr>
            </table>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="addSubmit">保存</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>





    <script src="//unpkg.com/layui@2.11.0/dist/layui.js"></script>
    <script>
        layui.use(['table', 'layer', 'jquery','laypage','form'], function () {
            var table = layui.table,
                layer = layui.layer,
                laypage = layui.laypage,
                form =layui.form,
                $ = layui.jquery;
                var totalCount=0;



                // 初始化表格
                table.render({
                    elem: '#test',
                    id: 'Roletable',
                    height: '600',
                    cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'roleId', fixed: 'left', width: 80, title: 'ID', sort: true, totalRow: '合计：' },
                    { field: 'roleName', title: '角色名称' },
                    { field: 'roleDesc', title: '角色描述' },
                    { field: 'isUsed', title: '是否启用', templet: function (d) {
                        return d.isUsed ? '是' : '否';
                    }},
                    { field: 'createTime', title: '添加时间' },
                    { fixed: 'right', title: '操作', width: 120, templet: '#toolDemo' }
                ]],
                    page: true, // 开启分页
                    limit: 15, // 默认每页显示15条
                    limits: [2, 15, 30, 50] // 可选每页显示条数
                });


                function loadRoleData(PageIndex, PageSize) {
                    layer.load(2);
                    var Title = $('[name="Title"]').val();
                    var params = {
                        PageIndex: PageIndex || 1, // 默认第一页
                        PageSize: PageSize || 15,   // 默认每页15条
                        RoleName: Title
                    }
                    $.ajax({
                        url:  `@ViewBag.BaseUrl/T5/Role/GetRole`,                      
                        data: params,
                        type: 'get',
                        dataType: 'json',
                        success: function (res) {
                            console.log(res.totalCount);
                            layer.closeAll('loading');
                            if (res.code === 0) {
                                totalCount=res.totalCount;
                                table.reload('Roletable', {
                                    data: res.data,
                                    count: res.totalCount,
                                    limit: PageSize || 15,
                                    curr: PageIndex || 1,
                                });

                                //分页
                                laypage.render({
                                    count: res.totalCount, // 数据总数
                                    curr: PageIndex,
                                    limit: PageSize,
                                    limits: [2, 15, 30, 50],
                                    layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'],
                                    jump: function (obj, first) {
                                        if (!first) {
                                            loadRoleData(obj.curr, obj.limit);
                                        }
                                    }
                                });

                            } else {
                                layer.msg('获取数据失败: ' + (res.message || '未知错误'), { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            layer.closeAll('loading');
                            layer.msg('请求失败: ' + error, { icon: 2 });
                            console.error('Ajax请求失败:', xhr.responseText);
                        }
                    });
                }
                // 页面加载完成后获取数据
                loadRoleData(1, totalCount);


            // 行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    // 打开编辑弹窗
                    layer.open({
                        type: 1,
                        title: '编辑管理员',
                        area: ['60%', '60%'],
                        content: $('#addDialog'),
                        success: function () {
                            // 重置表单
                            $('#addForm')[0].reset();
                            // 回显数据
                            form.val('addForm', {
                                roleName: data.roleName,
                                roleDesc: data.roleDesc,
                                IsUsed: data.isUsed
                            });
                            form.render();
                        }
                    });
                    // 存储当前编辑的数据 ID
                    $('#addForm').data('roleId', data.roleId);
                }
            });


            // 优化后的分页处理（移除冗余的reload调用，Layui自动处理分页）
            table.on('page(test)', function (obj) {
                console.log('当前页：', obj.curr, '每页数量：', obj.limit);
            });

            // 移除冗余的dropdown和行模式代码（根据需求保留核心功能）


            // 表单提交事件
            form.on('submit(search)', function () {
                loadRoleData();
                return false;
            });

            // 新增按钮点击事件
            $('#addRole').on('click', function () {
                layer.open({
                    type: 1,
                    title: '新增管理员',
                    area: ['60%', '60%'],
                    content: $('#addDialog'),
                    success: function () {
                        // 重置表单
                        $('#addForm')[0].reset();
                        form.render();
                    }
                });
                // 清除存储的角色 ID
                $('#addForm').removeData('roleId');
            });

            // 新增/编辑表单提交
            form.on('submit(addSubmit)', function (data) {
                var formData = data.field;
                var roleId = $('#addForm').data('roleId');
                var isEdit = typeof roleId!== 'undefined';
                var postData = {
                    roleId: roleId || 0,
                    roleName: formData.roleName,
                    roleDesc: formData.roleDesc,
                    isUsed: $('#IsUsed').prop('checked'),
                    createUserId: 0,
                    createTime: formData.createTime,
                    updateUserId: 0,
                    updateTime: formData.updateTime,
                    deletedUserId: 0,
                    deleteTime: formData.deleteTime,
                    isDeleted: false
                };

                layer.load(2);
                $.ajax({
                    url: isEdit? `@ViewBag.BaseUrl/T6/Role/UpdateRole` : `@ViewBag.BaseUrl/T6/Role/AddRole`,
                    type: isEdit? 'post' : 'post',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    dataType: 'json',
                    success: function (res) {
                        layer.closeAll('loading');
                        if (res.code == 100) {
                            layer.alert(res.test, {
                                title: '操作成功',
                                icon: 1,
                                btn:['确定'],
                                yes: function (index, layero) {
                                    document.getElementById("addForm").reset();
                                    form.render();
                                    layer.close(index);
                                    layer.closeAll(); // 关闭所有弹层
                                    loadRoleData(); // 刷新表格数据
                                }
                            });
                        } else {
                            layer.alert(res.test, {
                                title: '操作失败',
                                icon: 2
                            });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.closeAll('loading');
                        layer.alert('请求失败: ' + error, {
                            title: '错误',
                            icon: 2,
                            btn: ['确定']
                        });
                        console.error('AJAX请求失败:', status, error);
                        console.error('响应内容:', xhr.responseText);
                    }
                });
                return false;
            });


        });
    </script>
</body>

</html>
